package com.ruiao.car.config;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.thymeleaf.util.StringUtils;

import java.util.Locale;

@Component
public class SpringContextUtil implements ApplicationContextAware {

    public static final String QA="qa";
    public static final String PRD="prd";


    private static ApplicationContext context = null;


    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        SpringContextUtil.context = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return context;
    }


    // 传入线程中
//    public static <T> T getBean(Class<CandyService> beanName) {
//        return (T) context.getBean(beanName);
//    }

    public static Object getBean(Class c) {
        return context.getBean(c);
    }

    public static Object  getBean(String name,Object... args) {
        return getApplicationContext().getBean(name,args);
    }

    // 国际化使用
    public static String getMessage(String key) {
        return context.getMessage(key, null, Locale.getDefault());
    }


    /// 获取当前环境
    public static String getActiveProfile() {
        if(context.getEnvironment().getActiveProfiles()!=null) {
            return context.getEnvironment().getActiveProfiles()[0];
        } else {
            return null;
        }
    }

    //是否为测试环境
    public static boolean isQa(){
        String activeProfile = getActiveProfile();
        if( !StringUtils.isEmpty(activeProfile) && activeProfile.equals(QA)){
            return true;
        }
        return false;
    }

    public static boolean isNotPrd(){
        String activeProfile = getActiveProfile();
        if( !StringUtils.isEmpty(activeProfile) && !activeProfile.equals(PRD)){
            return true;
        }
        return false;
    }

}